require('es6-promise').polyfill();

import axios from 'axios'

export function createPropertyData(data) {
  return {
    type: 'CREATE_Property_DATA',
    data,
    date: Date.now()
  }
}
export function editPropertyData(data) {
  return {
    type: 'EDIT_Property_DATA',
    data,
    date: Date.now()
  };
}
export function deletePropertyData(id) {
  return {
    type: 'DELETE_Property_DATA',
    id
  };
}

export function apiMsgAction(msg) {
  return {
    type: 'API_MSG',
    msg
  }
}

function loadPropertyData(data) {
  return {
    type: 'LOAD_Property_DATA',
    data
  }
}

function errorAction(error) {
  return {
    type: 'ERROR_PROPERTY',
    error
  }
}


export function deletePropertyAsync(data) {
  return function(dispatch) {
    return axios.post('/api/property/delete', data).then(
      resp => dispatch(deletePropertyData(data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    )
  }
}


export function createPropertyAsync(data) {
  console.log("create")
  return function(dispatch) {
    return axios.post('/api/property/create', data).then(
      resp => dispatch(createPropertyData(resp.data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    )
  }
}

export function loadPropertyDataAsync(filter) {
  var url = '/api/property';
  if (filter && filter.name && filter.name.length > 0) {
    url += '?name='+filter.name
  }
  return function(dispatch) {
    return axios.post(url, filter).then(
      resp => dispatch(loadPropertyData(resp.data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    )
  }
}

export function syncPropertyDataAsync() {
  return function(dispatch) {
    return axios.post('/api/property/sync').then(function(resp) {
      alert("同步完成")
      stopProgress()
    })
    .catch(function(error) {
      alert(error.data.errMsg)
      stopProgress()
    })
  }
}


export function editPropertyDataAsync(data) {
  return function(dispatch) {
    return axios.post('/api/property/update', data).then(
      resp => dispatch(editPropertyData(data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    )
  }
}
